using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using SubSonic.Query;
using SubSonic.Repository;
using SubSonic.Schema;
using TaoSharp.Core.Domain;

namespace TaoSharp.Core
{
    public class DataRepository 
    {
        private readonly SimpleRepository _repository;

        public DataRepository()
        {
            _repository = new SimpleRepository("TaoSharpConnectionString", SimpleRepositoryOptions.RunMigrations);
        }

        public int Add<T>(CommonItem item) where T:class, new()
        {
            _repository.Add(item as T);

            return item.Id;
        }

        public T Select<T>(int id) where T:class, new()
        {
            return _repository.Single<T>(id);
        }

        public IQueryable<T> SelectAll<T>() where T:class, new()
        {
            return _repository.All<T>();
        }

        public IList<T> Find<T>(Expression<Func<T, bool>> findQuery) where T : class, new()
        {
            return _repository.Find(findQuery);
        }

        public int Count<T>(Expression<Func<T, bool>> countQuery)
        {
            return (int)new Select(Aggregate.Count("Name")).From<T>().Where(countQuery).ExecuteScalar();
        }
    }
}